<template>
  <!-- $fileUploadUrl 全局定义 -->
  <el-upload ref="elupload" :action="fileUploadUrl" v-bind="$attrs" :handleExceed="handleExceed" :on-remove="onRemove" :on-error="onError" :on-preview="onPreview">
    <slot></slot>
    <template #trigger>
      <slot name="trigger"></slot>
    </template>
    <template #tip>
      <slot name="tip"></slot>
    </template>

    <!-- 图片预览 -->
    <el-dialog :visible.sync="previewDialog.visible">
      <img width="100%" v-if="previewDialog.imageUrl" :src="previewDialog.imageUrl" alt="">
    </el-dialog>
  </el-upload>
</template>

<script>
export default {
  name: 'StElUpload',
  props: {
    uploadUrl: String
  },
  computed:{
    fileUploadUrl() {
      return this.uploadUrl || this.$stObjectTools.getValue(this.$scatterConfig,'StElUpload.fileUploadUrl') || '/file/cloudstorage/upload'
    },
  },
  data(){
    return {
      previewDialog: {
        visible: false,
        imageUrl: ''
      }
    }
  },
  methods:{
    getUploadRef() {
      return this.$refs.elupload
    },
    handleExceed(files, fileList){
      if (this.$attrs.handleExceed) {
        this.$attrs.handleExceed(files, fileList)
      }else {
        this.$message.warning(`当前限制选择 ${this.$attrs.limit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      }
    },
    onRemove(file, fileList) {
      if (this.$attrs.onRemove) {
        this.$attrs.onRemove(file, fileList)
      }
      let deleteUrl = ''
      // 如果存在是上传响应对象
      if (file.response) {
        deleteUrl = file.response.url
      }
      // 已上传初始化的数据
      else {
        deleteUrl =  file.url
      }
      this.doDelete(deleteUrl)
    },
    doDelete(deleteUrl) {
      if (deleteUrl) {
        this.axios.delete(deleteUrl);
      }
    },
    onError(err, file, fileList) {
      if (this.$attrs.onError) {
        this.$attrs.onError(err, file, fileList)
      }else
      if (err.message) {
        let errorVo = JSON.parse(err.message)
        if (errorVo.errorMsg) {
          this.$message.error(errorVo.errorMsg);
        }
      }
    },
    // 预览文件
    onPreview (file){
      if (this.$attrs.onPreview) {
        this.$attrs.onPreview(file)
      }else{
        this.defaultPreview(file.url)
      }
    },
    defaultPreview(url) {
      if(this.$attrs.accept && this.$attrs.accept.indexOf('image') >=0 || this.$stStringTools.endWithAny(file.url,['jpg','jpeg','png','gif'],true)){
        this.previewDialog.imageUrl = url
        this.previewDialog.visible = true;
      }else{
        this.$message.info('目前只支持图片预览');
      }
    }
  }
};
</script>
